<template>
    <div class="map">
        <van-swipe :autoplay="3000">
            <van-swipe-item v-for="(image, index) in images" :key="index">
                <img style="width: 100%; height: 50vw" :src="image" />
            </van-swipe-item>
        </van-swipe>
        <van-search v-model="gcb_name" placeholder="请输入使用人姓名" @search="onSearch" />
        <van-search v-model="c_nam" placeholder="请输入认购人姓名" @search="onSearch" />
        <van-search v-model="gm_ex6" placeholder="请输入墓位编号 例: 中南区1-1" @search="onSearch" />
        <van-search v-model="c_ex13" :show-action="false" placeholder="请输入家属身份证" @search="onSearch">
            <!-- <template #action>
				<div @click="onSearch">搜索</div>
			</template> -->
        </van-search>
        <van-button type="primary" block size="small" @click="onSearch">搜索墓位</van-button>

        <PullRefreshList
            v-model:refreshing="refreshing"
            v-model:loading="loading"
            v-model:finished="finished"
            v-model:list="list"
            @load="onLoad"
        >
            <div v-for="(item, index) in list" :key="index" class="content">
                <div class="img">
                    <img :src="item.gm_ex27" />
                    <!-- <img :src="item.img" > -->
                    <!-- <div v-html="item.imgurl"></div> -->
                </div>
                <div class="font">
                    <div>{{ item.address }}</div>
                    <div>使用人姓名：{{ item.gcb_name }}</div>
                    <div>认购人姓名：{{ getDesensitizeNameStr(item.c_nam) }}</div>
                    <div>身份证：{{ getDesensitizeIdCardStr(item.c_ex13) }}</div>
                    <div>墓位编号：{{ item.gm_ex6 }}</div>
                    <template v-if="route.path == '/businessInquiry'">
                        <!-- <div>
							<van-button type="primary" size="small" style="margin-right: 1vw" @click.stop="$router.push(`/cloudSacrificePersonalHall?th_id=${item.gm_id}`)">云祭祀</van-button>
							<van-button type="primary" size="small" @click.stop="showP(item)">云祭祀二维码</van-button>
						</div> -->
                    </template>
                    <div v-else>
                        <van-button type="primary" size="small" @click.stop="renew(item)">墓位续费</van-button>
                    </div>
                </div>
            </div>
        </PullRefreshList>
        <van-popup v-model:show="showPopup1" :style="{ padding: '5vw' }">
            <div v-html="imgUrl"></div>
        </van-popup>
        <van-popup v-model:show="showPopup2" round>
            <div class="pupup-title">墓位续费</div>
            <van-form show-error scroll-to-error label-width="25vw" @submit="onSubmit" @failed="onFailed">
                <van-field
                    v-model="formData.address"
                    required
                    center
                    name="address"
                    label="墓位地址"
                    placeholder="墓位地址"
                    :rules="[{ required: true, message: '请填写墓位地址' }]"
                />
                <van-field
                    v-model="formData.c_nam"
                    required
                    center
                    name="c_nam"
                    label="联系人"
                    placeholder="联系人"
                    :rules="[{ required: true, message: '请填写联系人' }]"
                />
                <van-field
                    v-model="formData.c_ex18"
                    required
                    center
                    name="c_ex18"
                    label="联系电话"
                    placeholder="联系电话"
                    maxlength="11"
                    :rules="[
                        { required: true, message: '请填写联系电话' },
                        { validator: isPhone, message: '请填写正确的联系电话' },
                    ]"
                />
                <van-field
                    v-model="formData.date1"
                    readonly
                    required
                    center
                    name="date1"
                    label="续费开始时间"
                    placeholder="续费开始时间"
                    :rules="[{ required: true, message: '请填写续费开始时间' }]"
                />
                <van-field
                    v-model="formData.dateNum"
                    type="digit"
                    required
                    center
                    name="dateNum"
                    label="续费年数"
                    placeholder="续费年数"
                    :rules="[{ required: true, message: '请填写续费年数' }]"
                    @update:model-value="dateNumChange"
                >
                    <template #button>
                        <van-stepper v-model="formData.dateNum" min="1" integer disable-input />
                    </template>
                </van-field>
                <van-field
                    v-model="formData.date2"
                    readonly
                    required
                    center
                    name="date2"
                    label="续费到期时间"
                    placeholder="续费到期时间"
                    :rules="[{ required: true, message: '请填写续费到期时间' }]"
                />
                <van-field
                    v-model="formData.mx_ex7"
                    type="number"
                    readonly
                    required
                    center
                    name="mx_ex7"
                    label="年管理费"
                    placeholder="年管理费"
                    :rules="[{ required: true, message: '请填写年管理费' }]"
                />
                <van-field
                    v-model="formData.money"
                    type="number"
                    readonly
                    required
                    center
                    name="money"
                    label="续费金额"
                    placeholder="续费金额"
                    :rules="[{ required: true, message: '请填写续费金额' }]"
                />
                <FixedButton native-type="submit">支付</FixedButton>
            </van-form>
        </van-popup>
    </div>
</template>

<script lang="ts" setup>
    // import { ref, reactive, markRaw } from 'vue';
    import type { Ref, Raw } from 'vue';
    // import { showDialog, showLoadingToast, closeToast, showFailToast } from 'vant';
    import { useRouter, useRoute } from 'vue-router';
    import FixedButton from '@/components/fixedButton/FixedButton.vue';
    import PullRefreshList from '@/components/pullRefreshList/PullRefreshList.vue';

    // import wx from "weixin-js-sdk";
    // import jsrsasign from 'jsrsasign';
    import {
        WSJSYTJApi,
        WXZFXFApi,
        weixinCgiBinAccessTokenApi,
        weixinGetticketApi,
        jsapiApi,
        wechatPayApi,
    } from '@/apis';
    import { getDesensitizeNameStr, getDesensitizeIdCardStr, isPhone } from '@/utils';

    import { useStore } from '@/store';
    import { useWeixinLogin3 } from '@/hooks';

    const route = useRoute();
    const router = useRouter();
    const store = useStore();
    // 微信授权并且跳转到对应页面
    if (route.path != '/businessInquiry') {
        useWeixinLogin3('renew');
    }
    console.log(route.path);
    const images: Raw<string[]> = markRaw([new URL('@/assets/img/banner/gmjs_bg17.png', import.meta.url).href]);
    const list: Ref<Array<any>> = ref([]);
    const loading: Ref<boolean> = ref(false);
    const finished: Ref<boolean> = ref(false);
    const showPopup1: Ref<boolean> = ref(false);
    const showPopup2: Ref<boolean> = ref(false);
    const refreshing: Ref<boolean> = ref(true);
    const gcb_name: Ref<string> = ref('');
    const c_nam: Ref<string> = ref('');
    const c_ex13: Ref<string> = ref('');
    const gm_ex6: Ref<string> = ref('');
    const imgUrl: Ref<string> = ref('');
    const formData = reactive({
        date1: '',
        date2: '',
        dateNum: 0,
        money: 0,
        gm_ex33: '',
        address: '',
        c_ex18: '',
        c_nam: '',
        mx_ex7: 0, //年管理费
    });

    const onSearch = async () => {
        if (!gcb_name.value && !c_ex13.value && !gm_ex6.value && !c_nam.value) {
            showDialog({
                title: '提示',
                message: '请输入使用人姓名，墓位编号或者家属身份证！',
            });
        } else {
            showLoadingToast({
                message: '加载中...',
                forbidClick: true,
                duration: 0,
            });
            let val: any = await WSJSYTJApi({
                gcb_name: gcb_name.value,
                c_nam: c_nam.value,
                c_ex13: c_ex13.value,
                gm_ex6: gm_ex6.value,
            });
            closeToast();
            list.value = val;
            if (list.value.length == 0) {
                showFailToast('暂无数据！');
            }
            console.log(list.value);
        }
    };

    const onLoad = async (callback) => {
        console.log(callback);
        // if (refreshing.value) {
        // 	list.value = [];
        // 	refreshing.value = false;
        // }
        if (gcb_name.value || c_ex13.value || gm_ex6.value || c_nam.value) {
            let val: any = await WSJSYTJApi({
                c_ex13: c_ex13.value,
                gm_ex6: gm_ex6.value,
                gcb_name: gcb_name.value,
                c_nam: c_nam.value,
            });
            list.value.push(...val);
        }

        callback(true);
    };
    const showP = (val) => {
        showPopup1.value = true;
        imgUrl.value = val.imgurl;
    };
    const renew = (val) => {
        showLoadingToast({
            message: '加载中...',
            forbidClick: true,
            duration: 0,
        });
        WXZFXFApi({
            sId: val.gm_id,
        })
            .then((res) => {
                console.log(res[0]);
                showPopup2.value = true;
                formData.date1 = res[0].gmdat4;
                formData.gm_ex33 = res[0].gm_ex33;
                formData.address = val.address;
                formData.c_ex18 = val.c_ex18;
                formData.c_nam = val.c_nam;

                let ddate = new Date(res[0].gmdat4);
                let yyear = ddate.getFullYear();
                console.log(yyear);
                let time2 = new Date(new Date(ddate).setFullYear(yyear + 1));
                console.log(time2);
                let year2 = time2.getFullYear();
                console.log(year2);
                let month2 = (time2.getMonth() + 1).toString().padStart(2, '0');
                console.log(month2);
                let date2 = time2.getDate().toString().padStart(2, '0');
                console.log(date2);
                formData.date2 = year2 + '-' + month2 + '-' + date2;

                formData.dateNum = 1;
                formData.mx_ex7 = res[0].mx_ex7;
                formData.money = res[0].mx_ex7;
            })
            .catch((err) => {})
            .finally(() => {
                closeToast();
            });
    };
    const dateNumChange = (val) => {
        console.log(val);
        let time2 = new Date(
            new Date(formData.date1).setFullYear(new Date(formData.date1).getFullYear() + Number(val))
        );
        console.log(time2);
        let year2 = time2.getFullYear();
        let month2 = (time2.getMonth() + 1).toString().padStart(2, '0');
        let date2 = time2.getDate().toString().padStart(2, '0');
        formData.date2 = year2 + '-' + month2 + '-' + date2;
        formData.money = formData.mx_ex7 * val;
    };
    const onFailed = (value) => {
        showDialog({
            title: '提示',
            message: value.errors[0].message,
        });
    };

    const onSubmit = async (value) => {
        showLoadingToast({
            message: '加载中...',
            forbidClick: true,
            duration: 0,
        });
        try {
            // let res1 = await weixinCgiBinAccessTokenApi({
            // 	grant_type: 'client_credential',
            // 	appid: 'wx8c16179b5b100339',
            // 	secret: 'acd91a6cac2144fec8a1c684fae2b09e',
            // })
            // let res2 = await weixinGetticketApi({
            // 	access_token: res1.access_token,
            // 	type: 'jsapi',
            // })
            // wx.config({
            // 	debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            // 	appId: 'wx8c16179b5b100339', // 必填，公众号的唯一标识
            // 	timestamp: new Date().getTime(), // 必填，生成签名的时间戳
            // 	nonceStr: '', // 必填，生成签名的随机串
            // 	signature: '',// 必填，签名
            // 	jsApiList: [] // 必填，需要使用的JS接口列表
            // });
            let dat = {
                openid: store.wxOpenid,
                ...formData,
            };
            console.log(JSON.stringify(dat));
            // alert(JSON.stringify(dat))
            let res1 = await wechatPayApi({
                openid: store.wxOpenid,
                ...formData,
            });
            // 第二个参数需要后端返回签名认证
            // let res2 = await jsapiApi({
            // 	appid: res1.wxAppId, //公众号ID
            // 	mchid: '1656768053', //直连商户号
            // 	description: '墓位续费', //商品描述
            // 	out_trade_no: res1.wxNonceStr, //商户系统内部订单号，只能是数字、大小写字母_-*且在同一个商户号下唯一。
            // 	// out_trade_no: new Date().getTime().toString() + Math.floor(Math.random()*1000000).toString().padStart(6, '0'), //商户系统内部订单号，只能是数字、大小写字母_-*且在同一个商户号下唯一。
            // 	notify_url: 'http://ysx.tianxunwang.com/fhsWeixin/renew', // 异步接收微信支付结果通知的回调地址，通知URL必须为外网可访问的URL，不能携带参数。 公网域名必须为HTTPS，如果是走专线接入，使用专线NAT IP或者私有回调域名可使用HTTP
            // 	amount: {
            // 		total: formData.money * 100 //订单总金额，单位为分。
            // 	}, //订单金额信息
            // 	payer: {
            // 		openid: store.wxOpenid //用户在普通商户AppID下的唯一标识。
            // 	}, // 支付者信息。
            // }, res1.wxPaySign)
            if (typeof WeixinJSBridge == 'undefined') {
                if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                } else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                    document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                }
            } else {
                onBridgeReady(res1);
            }
        } catch (error) {
            showDialog({
                title: '提示',
                message: '网络异常，请稍后重试！',
            });
        } finally {
            closeToast();
        }
    };
    const onBridgeReady = (res1) => {
        // let appId = "wx8c16179b5b100339"
        let appId = res1.wxAppId;
        let timestamp = res1.wxTimeStamp;
        let nonceStr = res1.wxNonceStr;
        let package1 = res1.wxPackage;
        let paySign = res1.wxPaySign;
        let signType = res1.wxSignType;
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest',
            {
                appId: appId, //公众号ID，由商户传入
                timeStamp: timestamp, //时间戳，自1970年以来的秒数
                nonceStr: nonceStr, //随机串
                package: package1,
                // "signType": "RSA",     //微信签名方式
                signType: signType, //微信签名方式
                // "paySign": "oR9d8PuhnIc+YZ8cBHFCwfgpaK9gd7vaRvkYD7rthRAZ\/X+QBhcCYL21N7cHCTUxbQ+EAt6Uy+lwSN22f5YZvI45MLko8Pfso0jm46v5hqcVwrk6uddkGuT+Cdvu4WBqDzaDjnNa5UK3GfE1Wfl2gHxIIY5lLdUgWFts17D4WuolLLkiFZV+JSHMvH7eaLdT9N5GBovBwu5yYKUR7skR8Fu+LozcSqQixnlEZUfyE55feLOQTUYzLmR9pNtPbPsu6WVhbNHMS3Ss2+AehHvz+n64GDmXxbX++IOBvm2olHu3PsOUGRwhudhVf7UcGcunXt8cqNjKNqZLhLw4jq\/xDg==" //微信签名
                paySign: paySign, //微信签名
            },
            function (res) {
                console.log(res);
                if (res.err_msg == 'get_brand_wcpay_request:ok') {
                    // 使用以上方式判断前端返回,微信团队郑重提示：
                    //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                    this.$router.push('/renewalRecord');
                } else {
                    showDialog({
                        title: '提示',
                        message: '续费异常，请稍后重试！',
                    });
                }
            }
        );
    };
</script>

<style lang="scss" scoped>
    .map {
        width: 100vw;
        height: 100vh;
        overflow: hidden;
        display: flex;
        flex-direction: column;
    }
    :deep(.van-pull-refresh) {
        overflow: scroll;
        flex: 1;
    }
    .content {
        display: flex;
        justify-content: space-around;
        align-items: center;
        height: 40vw;
    }
    .content > .img {
        width: 30vw;
        height: 30vw;
    }
    .content > .img img {
        width: 100%;
        height: 100%;
    }
    .content > .font {
        width: 60vw;
        // height: 38vw;
        height: 34vw;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }
    .content > .font > div {
        overflow: hidden;
        /* white-space: nowrap;
		text-overflow: ellipsis; */
        color: #212121;
        text-align: left;
    }
    .content > .font > div:first-child {
        font-weight: bold;
        color: #181818;
    }
    .pupup-title {
        text-align: center;
        font-size: 16px;
        padding: 10px;
    }
</style>
